package com.example.intercepter;

import com.example.pojo.Result;
import com.example.utils.JwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */
public class LoginIntercepter implements HandlerInterceptor {

    /**
     * 拦截方法权限校验
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        ObjectMapper objectMapper = new ObjectMapper();

        //从请求中获取token信息
        String token = request.getParameter("token");
        if (token == null) {
            token = request.getHeader("token");
        }
        if (token == null || token.trim() == "") {
            //响应错误结果
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(objectMapper.writeValueAsString(new Result(500, null, "用户未登录")));
            return false;
        }
        //验证token是否过期
        if (!JwtUtil.validateToken(token)) {
            //响应错误结果
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(objectMapper.writeValueAsString(new Result(500, null, "用户登录过期，请重新登录")));
            return false;
        }
        return true;
    }
}
